package com.wwj.study.spring.formework.context.support;

import com.wwj.study.spring.formework.beans.WBeanDefinition;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @Author: wuweijun
 * @Date: 2018/12/1 20:57
 */
public class WBeanDefinitionReader {

    //配置文件
    private Properties properties =new Properties();

    //在配置文件中，用来获取自动扫描的包名的key
    private final String SCAN_PACKAGE = "scanPackage";

    //需要注册到IOS容器中的类集合
    private List<String> registyBeanClasses = new ArrayList<String>();

    public WBeanDefinitionReader(String... locations){
        //加载配置文件
        doLoadConfig(locations[0]);
        //读取scanPackage包
        doScanner(properties.getProperty(SCAN_PACKAGE));
    }

    //根据配置文件中的路径，读取需要注册到IOC容器中的所有类，放入集合registyBeanClasses
    //文件夹递归茶查找
    private void doScanner(String packageName){
        URL url = this.getClass().getClassLoader().getResource("/" + packageName.replaceAll("\\.","/"));
        File classDir = new File(url.getFile());
        for (File file : classDir.listFiles()){
            if(file.isDirectory()){
                doScanner(packageName + "." +file.getName());
            }else {
                registyBeanClasses.add(packageName + "." + file.getName().replace(".class",""));
            }
        }

    }

    //传入配置文件路径
    //读取配置文件，存入properties
    private void doLoadConfig(String config) {
        InputStream inputStream=null;
        try {
            inputStream= this.getClass().getClassLoader().getResourceAsStream(config.replace("classpath:",""));
            properties.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public List<String> loadBeanDefinitions(){
        return registyBeanClasses;
    }

    //注册BeanDefinition
    //BeanClassName Bean对象的包全路径
    //FactoryBeanName 别名
    public WBeanDefinition registerBean(String bean){
        if(registyBeanClasses.contains(bean)){
            WBeanDefinition wBeanDefinition=new WBeanDefinition();
            wBeanDefinition.setBeanClassName(bean);
            wBeanDefinition.setFactoryBeanName(lowerFirstCase(bean.substring(bean.lastIndexOf(".") + 1)));
            return wBeanDefinition;
        }
        return null;
    }

    //首字母转小写
    private String lowerFirstCase(String str){
        char [] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

    public Properties getProperties() {
        return properties;
    }
}
